/*
package com.cloud.tsp.consumer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.api.constants.SmsTemplates;
import com.cloud.api.domain.alarm.AlarmCategory;
import com.cloud.api.domain.alarm.VehicleAlarm;
import com.cloud.api.domain.tsp.VehicleSale;
import com.cloud.api.mq.AlarmMsg;
import com.cloud.api.mq.VehicleAlarmRequest;
import com.cloud.api.myenum.AlarmLevelEnum;
import com.cloud.api.myenum.AlarmTypeEnum;
import com.cloud.core.exception.MyException;
import com.cloud.tsp.config.MapConfig;
import com.cloud.tsp.mapper.VehicleAlarmMapper;
import com.cloud.tsp.service.IVehicleSaleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Consumer;

@Slf4j
@Component
public class AlarmConsumer {

    @Autowired
    private StreamBridge streamBridge;
    @Resource
    private SmsTemplates smsTemplates;
    @Resource
    private VehicleAlarmMapper vehicleAlarmMapper;
    @Resource
    private IVehicleSaleService vehicleSaleService;
    @Autowired
    private MapConfig mapConfig;
    @Value("${spring.application.name}")
    private String logName;
    @Resource(name = "myRedis")
    private RedisTemplate<String,Object> redisTemplate;

    @Bean
    Consumer<VehicleAlarmRequest> tspalarm() {
        log.info("订阅成功");
        return msg -> {
//            log.info("通过stream消费到消息 => {}", msg.getVin());
            //通过code查询方案表是否开启了短信通知
            AlarmCategory alarmCategory = (AlarmCategory) redisTemplate.opsForHash().get("ALARM-CATEGORY", msg.getAlarmType().toString());
            //查询销售数据vin信息
            VehicleSale vehicleSale = (VehicleSale) redisTemplate.opsForHash().get("VIN-INFORMATION", msg.getVin());
            if (vehicleSale == null){
                VehicleSale sale = vehicleSaleService.selectVehicleSaleByVin(msg.getVin());
                if (sale == null){
                    log.error("未找到该vin数据");
                    //保存遗漏vin数据日志
                    saveErr(msg.getVin());
                    return;
                }else {
                    vehicleSale = sale;
//                    redisTemplate.opsForHash().put("VIN-INFORMATION",msg.getVin(),vehicleSale);
                }
            }
            //保存报警信息
            String location = saveAlarm(msg, vehicleSale, alarmCategory);

            if (alarmCategory.getSmsStatus() == 1 && vehicleSale.getPhoneNumber()!=null) {
                AlarmMsg alarmMsg = new AlarmMsg();
                alarmMsg.setAlarm(AlarmLevelEnum.getDesc(msg.getLevel()));
                alarmMsg.setPlateNo(vehicleSale.getLicenseNumber());
                alarmMsg.setVin(msg.getVin());
                alarmMsg.setTime(LocalDateTimeUtil.format(msg.getLocalDateTime(), DatePattern.NORM_DATETIME_PATTERN));
                alarmMsg.setLocate(location);
                alarmMsg.setTemplate(smsTemplates.getAlarmTemplate());
                alarmMsg.setMobile(vehicleSale.getPhoneNumber());
                JSONObject json = JSONUtil.parseObj(alarmMsg);
                streamBridge.send("alarmSms-out-0", MessageBuilder.withPayload(json).build());
//                mySmsService.sendSms(alarmMsg.getMobile(), alarmMsg.getTemplate(), json);
            }
        };
    }

    public String saveAlarm(VehicleAlarmRequest msg, VehicleSale vehicleSale, AlarmCategory alarmCategory) {
        //翻译地址
        String location = getLocation(msg.getLat(), msg.getLng());

        VehicleAlarm vehicleAlarm = new VehicleAlarm();
        vehicleAlarm.setVin(msg.getVin());
        vehicleAlarm.setModelId(vehicleSale.getModelType());
        vehicleAlarm.setLicenseNumber(vehicleSale.getLicenseNumber());
        vehicleAlarm.setAlarmLevel(Integer.valueOf(msg.getLevel()));
        vehicleAlarm.setAlarmType(AlarmTypeEnum.getByValue(Integer.valueOf(alarmCategory.getCode())));
        vehicleAlarm.setAlarmAddress(location);
        vehicleAlarm.setAlarmTime(msg.getLocalDateTime());
        //保存
        vehicleAlarmMapper.insert(vehicleAlarm);
        return location;
    }


    public String getLocation(Long latData,Long lngData){
        String address = "";
        String lat = BigDecimal.valueOf(latData / 1000000.0).toString();
        String lng = BigDecimal.valueOf(lngData / 1000000.0).toString();
        String ak = mapConfig.getBaiduAk();
        String url = "https://%s/reverse_geocoding/v3/?ak=%s&output=json&extensions_poi=1&coordtype=wgs84ll&location=%s,%s";
        url = String.format(url,"api.map.baidu.com",ak,lat,lng);
        try {
            ResponseEntity<String> response = new RestTemplate().getForEntity(url, String.class);
            JSONObject resultJson = JSONUtil.parseObj(response.getBody());
            if (Integer.parseInt(resultJson.get("status").toString()) != 0) {
                throw new MyException(resultJson.get("message").toString());
            }
            JSONObject result = resultJson.getJSONObject("result");
            if (result.getStr("formatted_address_poi")!= null){
                address = result.getStr("formatted_address_poi");
            }else {
                address = result.getStr("formatted_address");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return address;
    }

    public void saveErr(String vin){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(new Date());
        String filePath = "../logs/"+logName+"/遗漏vin数据-"+dateStr+".log";
        File file = new File(filePath);
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
                BufferedReader br = new BufferedReader(new FileReader(file));) {
            String line;
            boolean vinExists = false;
            while ((line = br.readLine()) != null) {
                if (line.equals(vin)) {
                    vinExists = true;
                    break;
                }
            }
            if (!vinExists) {
                bw.newLine();
                bw.write(vin);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
*/
